package com.example.ymm.modules1.service.impl.ms;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.ymm.base.BaseServiceImpl;
import com.example.ymm.model.TableList;
import com.example.ymm.model.YmPageDto;
import com.example.ymm.modules1.entity.ms.*;
import com.example.ymm.modules1.entity.my.user.ViewDeptUser;
import com.example.ymm.modules1.mapper.ms.VckStockMapper;
import com.example.ymm.modules1.query.ms.*;
import com.example.ymm.modules1.service.dto.DbDeptUserQueryCriteria;
import com.example.ymm.modules1.service.dto.ms.MsWarehouseDto;
import com.example.ymm.modules1.service.ms.DDepartmentService;
import com.example.ymm.modules1.service.ms.DEmployeeService;
import com.example.ymm.modules1.service.ms.VckStockService;
import com.example.ymm.modules1.service.user.DbDeptUserService;
import com.example.ymm.util.DateKit;
import com.example.ymm.util.QueryHelpPlus;
import com.example.ymm.util.UtilValidate;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

@Service
@Slf4j
@DS("slave")
public class VckStockServiceImpl extends BaseServiceImpl<VckStockMapper, VckStock> implements VckStockService {

    @Autowired
    DbDeptUserService dbDeptUserService;
    @Autowired
    DEmployeeService dEmployeeService;

    @Override
    public TableList<VckStock> list(VckStockQueryCriteria criteria, YmPageDto pageDto) {
        getPage(pageDto);
//        PageHelper.offsetPage(ymPage.getPage(),ymPage.getPageSize());
        List<VckStock> maps = stockList(criteria);
        PageInfo<VckStock> pageInfo = new PageInfo<>(maps);
        TableList<VckStock> tableList=new TableList<>(pageInfo);
        return tableList;
    }

    @Override
    public TableList<VckStock> listNoRef(VckStockQueryCriteria criteria, YmPageDto ymPage) {
        getPage(ymPage);
        List<VckStock> maps = stockListNoRef(criteria);
        PageInfo<VckStock> pageInfo = new PageInfo<>(maps);
        TableList<VckStock> tableList=new TableList<>(pageInfo);
        return tableList;
    }

    public List<VckStock> queryAll(VckStockQueryCriteria criteria) {
        QueryWrapper predicate = QueryHelpPlus.getPredicate(VckStock.class, criteria);
        List<VckStock> result =baseMapper.selectList(predicate);
        return result;
    }


    @Override
    public List<MsWarehouseDto> warehouseList(MsWarehouseDtoQueryCriteria criteria) {
        return baseMapper.warehouseList(criteria);
    }

    @Override
    public List<VckStock> stockList(VckStockQueryCriteria criteria) {
        List<VckStock> vckStocks = baseMapper.stockList(criteria);
        for(VckStock v : vckStocks){
            if(UtilValidate.isNotEmpty(v.getResidueNum())){
                BigDecimal rate = new BigDecimal(v.getResidueNum()).divide(new BigDecimal(v.getNum()),2,BigDecimal.ROUND_HALF_UP);
                String color = null;
                double v1 = rate.doubleValue();
                if(v1<=0.1){
                    color = "#ff0021";//红
                }else if(v1<=0.2){
                    color = "#f97124";
                }else if(v1<=0.3){
                    color = "#f5e509";//黄
                }
                v.setColorResidue(v1);
                v.setColor(color);
            }
        }
        return vckStocks;
    }


    @Override
    public List<VckStock> stockListNoRef(VckStockQueryCriteria criteria) {
        return baseMapper.stockListNoRef(criteria);
    }

    @Override
    public TableList <CkOutbillList> outbillPageList(CkOutbillQueryCriteria criteria,YmPageDto ymPage) {
        getPage(ymPage);
        List<CkOutbillList> maps =outbillList(criteria);
        PageInfo<CkOutbillList> pageInfo = new PageInfo<>(maps);
        TableList<CkOutbillList> tableList=new TableList<>(pageInfo);
        return tableList;
    }

    @Override
    public List<CkOutbillList> outbillList(CkOutbillQueryCriteria criteria) {
        if(UtilValidate.isNotEmpty(criteria.getMonth())){
            String month = criteria.getMonth();
            String start=month+"-01 00:00:00";
            String end = DateKit.getNextMonthStartDate(start);
            criteria.setStartTime(start);
            criteria.setEndTime(end);
        }
        String userName = getUserName();
        if("黄丽红".equals(userName)){
            List<String> dnameIn=new ArrayList<>();
            dnameIn.add("仓储物流部OEM表组");
            dnameIn.add("仓储物流部DKL组");
            criteria.setDnameIn(dnameIn);
        }
        if("陈丽贞".equals(userName)){
            criteria.setDname("仓储物流部钟组");
        }

        List<CkOutbillList> maps = baseMapper.ywPostageWaitList(criteria);
        return maps;
    }

    @Override
    public List<CkOutbillList> outbillTotal(CkOutbillQueryCriteria criteria) {
        if(UtilValidate.isNotEmpty(criteria.getMonth())){
            String month = criteria.getMonth();
            String start=month+"-01 00:00:00";
            String end = DateKit.getNextMonthStartDate(start);
            criteria.setStartTime(start);
            criteria.setEndTime(end);
        }
        String userName = getUserName();
        if("黄丽红".equals(userName)){
            criteria.setDname("仓储物流部OEM表组");
        }
        if("陈丽贞".equals(userName)){
            criteria.setDname("仓储物流部钟组");
        }
        return baseMapper.outbillTotal(criteria);

    }


    @Override
    public JSONObject outbillDeptUser() {
        JSONObject jsonObject = new JSONObject();
        String deptId="107701131";
        String userName = getUserName();
        String selectUserName=null;
        if("黄丽红".equals(userName)){
            deptId="913132329";
        }
        if("陈丽贞".equals(userName)){
            deptId="107701131";
            selectUserName="陈丽贞，杨双敏，陈奕欣";
        }
        if(UtilValidate.isNotEmpty(deptId)){
            DbDeptUserQueryCriteria criteria=new DbDeptUserQueryCriteria();
            criteria.setDeptId(deptId);
            DynamicDataSourceContextHolder.clear();
            DynamicDataSourceContextHolder.push("master");
            List<ViewDeptUser> deptUserList = dbDeptUserService.getDeptUserList(criteria);
            jsonObject.put("userList",deptUserList);
            jsonObject.put("selectUser",selectUserName);
            return jsonObject;
        }
        return jsonObject;
    }




    @Override
    public TableList<ViewBaogonCailiao> pmcTableList(PmcQueryCriteria criteria, YmPageDto ymPage) {
        String userName =null;
        DEmployee userInfo = null;
        try {
            userName = getUserName();
            userInfo = dEmployeeService.getUserInfo(userName);
        }catch (Exception e) {
            e.printStackTrace();
        }
        getPage(ymPage);
        if(UtilValidate.isEmpty(criteria.getSortColumn())){
            criteria.setSortColumn("bdate");
            criteria.setSortOrder("asc");
        }

        boolean isYwUser=false;//是不是业务人员
        if(UtilValidate.isNotEmpty(userInfo)&&
                (userInfo.getDname().contains("营销")||userInfo.getDname().contains("销售"))){
            isYwUser=true;
            if(userName.contains("秀铃")){
                criteria.setYwCustomerNo("0501");
            }
            criteria.setYwUseName(userName);
        }


        List<ViewBaogonCailiao> maps =pmcQueryList(criteria);// pmcList
        List<String> biaoShiHaoIn=new ArrayList<>();
        for (ViewBaogonCailiao map : maps) {
            String biaoShiHao = map.getBiaoShiHao();
            biaoShiHaoIn.add(biaoShiHao);
        }
//        Map<String, String> queLiaos = getQueLiaos(biaoShiHaoIn);
//        for (ViewBaogonCailiao map : maps) {
//            String biaoShiHao = map.getBiaoShiHao();
//            String s = queLiaos.get(biaoShiHao);
//            map.setQueLiaos(s);
//            //计算未完成数量
//        }
        PageInfo<ViewBaogonCailiao> pageInfo = new PageInfo<>(maps);
        TableList<ViewBaogonCailiao> tableList=new TableList<>(pageInfo);
        return tableList;
    }

    public Map<String,String> getQueLiaos(QueLiaosQueryCriteria criteria){

        PmcQueryCriteria p1=new PmcQueryCriteria();
        p1.setBiaoShiHaoIn(criteria.getBiaoShiHaoIn());
        p1.setBuMenName(criteria.getBuMenName());
        p1.setIsQueLiao(1);
        List<ViewBaogonItem> viewBaogonItems = pmcItemList(p1);
        Map<String,String> resultMap=new HashMap<>();
        Map<String,List<String>> map=new HashMap<>();
        viewBaogonItems.forEach(item->{
            if(map.containsKey(item.getBiaoShiHao())){
                List<String> list = map.get(item.getBiaoShiHao());
                list.add(item.getMtname());
                map.put(item.getBiaoShiHao(),list);
            }else{
                List<String> itemMap=new ArrayList<>();
                itemMap.add(item.getMtname());

                map.put(item.getBiaoShiHao(),itemMap);

            }
        });
        Set<Map.Entry<String,List<String>>> entries = map.entrySet();
        for (Map.Entry<String, List<String>> entry : entries) {
            Map<String,String> itemMap=new HashMap<>();
            entry.getValue().forEach(item->{
                itemMap.put(item,item);
            });
            resultMap.put(entry.getKey(),String.join(",",itemMap.values()));
        };

        return resultMap;
    }


    @Override
    public Map<String, Integer> getQiTaoNum(QueLiaosQueryCriteria c1) {
        PmcQueryCriteria criteria=new PmcQueryCriteria();
        criteria.setBiaoShiHaoIn(c1.getBiaoShiHaoIn());
        criteria.setBuMenName(c1.getBuMenName());
        List<ViewBaogonItem> viewBaogonItems = pmcItemList(criteria);
        Map<String,Integer> resultMap=new HashMap<>();
        for (int i = 0; i < viewBaogonItems.size(); i++) {
            ViewBaogonItem item = viewBaogonItems.get(i);
            if(!resultMap.containsKey(item.getBiaoShiHao())){
                resultMap.put(item.getBiaoShiHao(),item.getQuantity());
            }else {
                if(resultMap.get(item.getBiaoShiHao())>item.getQuantity()){
                    resultMap.put(item.getBiaoShiHao(),item.getQuantity());
                }
            }
        }
        return resultMap;
    }

    @Override
    public List<ViewBaogonItem> pmcItemList(PmcQueryCriteria criteria) {
        return baseMapper.pmcItemList(criteria);
    }


    @Override
    public Map<String, Integer> getBaoZhuangZiLiao(List<String> biaoShiHaoIn) {
        return Collections.emptyMap();
    }

    @Override
    public BigDecimal sumBaoGonNum(BaoGonQueryCriteria criteria) {
        return baseMapper.sumBaoGonNum(criteria);
    }


    @Override
    public List<BomMaterial> orderBomList(PmcQueryCriteria pmcQueryCriteria) {
        return baseMapper.orderBomList(pmcQueryCriteria);
    }

    @Override
    public List<ViewBaogonCailiao> pmcQueryList(PmcQueryCriteria pmcQueryCriteria) {
        return baseMapper.pmcQueryList(pmcQueryCriteria);
    }

    @Override
    public List<ViewBaogonCailiao> baogongQueryList(PmcQueryCriteria pmcQueryCriteria) {
        return baseMapper.baogongQueryList(pmcQueryCriteria);
    }

    @Override
    public List<PmcWenJianGuiDto> pmcWenjianList(PmcQueryCriteria pmcQueryCriteria) {
        return baseMapper.pmcWenjianList(pmcQueryCriteria);
    }
}
